package com.github.io.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/8/24 9:56
 * Description: 自定义 WebSocket 处理器，实现 WebSocketHandler 接口实现相关接口
 */

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    // 创建线程安全的集合类
    private static CopyOnWriteArraySet<WebSocketSession> webSocketSessions = new CopyOnWriteArraySet<>();


    // 建立连接完成
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        System.out.println("连接建立完成............");
        webSocketSessions.add(webSocketSession);
    }


    // 接口客户端发送的消息，并进行处理消息
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println("message: " + message);
//        if (message.getPayloadLength() == 0) {
//            return;
//        }
        System.out.println("推送消息................");

        sendMessageToUser(new TextMessage("系统消息推送......."));
    }

    public  static void sendMessageToUser(TextMessage textMessage) {
        // 根据 session对应的id，找到对应的session 进行特定对象推送消息
        // 或者，对所有用户都进行推送
        if (webSocketSessions.isEmpty()) return;

        webSocketSessions.forEach(session -> {
            if (session != null && session.isOpen()) {
                try {
                    session.sendMessage(textMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    // 处理消息传输异常
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if (webSocketSession.isOpen()) {
            webSocketSession.close();
        }
        webSocketSessions.remove(webSocketSession);
    }


    // 连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

        System.out.println("连接关闭............");
        webSocketSessions.remove(webSocketSession);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
